import 'package:flutter/material.dart';

/// 图片飞向右下角悬浮按钮动画（可复用）
/// [context] 上下文
/// [itemKey] 当前列表 item 图片的 GlobalKey
/// [albumKey] 悬浮相册按钮的 GlobalKey
/// [imageUrl] 需要飞行动画的图片
Future<void> runFlyToAlbumAnimation(
    BuildContext context,
    GlobalKey itemKey,
    GlobalKey albumKey,
    String imageUrl,
    ) async {
  final overlay = Overlay.of(context);
  if (overlay == null) return;

  // 获取图片的全局位置 & 大小
  final RenderBox itemBox = itemKey.currentContext!.findRenderObject() as RenderBox;
  final itemPos = itemBox.localToGlobal(Offset.zero);
  final itemSize = itemBox.size;

  // 获取悬浮按钮的全局位置 & 大小
  final RenderBox albumBox = albumKey.currentContext!.findRenderObject() as RenderBox;
  final albumPos = albumBox.localToGlobal(Offset.zero);
  final albumSize = albumBox.size;

  // 创建 OverlayEntry
  final overlayEntry = OverlayEntry(builder: (context) {
    return _FlyImageAnimationWidget(
      startPos: itemPos,
      startSize: itemSize,
      endPos: Offset(
        albumPos.dx + (albumSize.width - itemSize.width) / 2,
        albumPos.dy + (albumSize.height - itemSize.height) / 2,
      ),
      endSize: Size(albumSize.width * 0.4, albumSize.height * 0.4),
      imageUrl: imageUrl,
    );
  });

  overlay.insert(overlayEntry);

  // 动画时长 700ms
  await Future.delayed(const Duration(milliseconds: 700));
  overlayEntry.remove();
}

/// 内部飞行动画 Widget
class _FlyImageAnimationWidget extends StatefulWidget {
  final Offset startPos;
  final Offset endPos;
  final Size startSize;
  final Size endSize;
  final String imageUrl;

  const _FlyImageAnimationWidget({
    required this.startPos,
    required this.endPos,
    required this.startSize,
    required this.endSize,
    required this.imageUrl,
  });

  @override
  State<_FlyImageAnimationWidget> createState() => _FlyImageAnimationWidgetState();
}

class _FlyImageAnimationWidgetState extends State<_FlyImageAnimationWidget>
    with SingleTickerProviderStateMixin {

  late AnimationController controller;
  late Animation<double> flyX;
  late Animation<double> flyY;
  late Animation<double> scale;
  late Animation<double> fade;

  @override
  void initState() {
    super.initState();

    controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );

    // 路径：线性移动即可
    flyX = Tween<double>(begin: widget.startPos.dx, end: widget.endPos.dx)
        .animate(CurvedAnimation(parent: controller, curve: Curves.easeInOut));

    flyY = Tween<double>(begin: widget.startPos.dy, end: widget.endPos.dy)
        .animate(CurvedAnimation(parent: controller, curve: Curves.easeInOut));

    // 先放大后缩小
    scale = TweenSequence([
      TweenSequenceItem(
        tween: Tween<double>(begin: 1.0, end: 1.4)
            .chain(CurveTween(curve: Curves.easeOut)), // 放大变慢
        weight: 40,
      ),
      TweenSequenceItem(
        tween: Tween<double>(begin: 1.4, end: 0.3)
            .chain(CurveTween(curve: Curves.easeIn)), // 缩小变快
        weight: 60,
      ),
    ]).animate(controller);

    fade = Tween<double>(begin: 1, end: 0.0).animate(
      CurvedAnimation(parent: controller, curve: Curves.easeIn),
    );
    controller.forward();
  }

  @ override
  void dispose() {
    controller.stop();
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: controller,
      builder: (context, child) {
        return Positioned(
          left: flyX.value,
          top: flyY.value,
          child: Opacity(
            opacity: fade.value,
            child: Transform.scale(
              scale: scale.value,
              child: Image.network(
                widget.imageUrl,
                width: widget.startSize.width,
                height: widget.startSize.height,
                fit: BoxFit.cover,
              ),
            ),
          ),
        );
      },
    );
  }
}
